<script lang="ts" setup>
import { onBeforeUnmount, onMounted, reactive } from "vue";
import * as echarts from 'echarts';
import { getSaleDataApi } from "@/api/total"

const dataset = reactive([]);
var myChart;

// 获取销售数据
const getSaleData = (cb) => {
    getSaleDataApi()
        .then((res: any) => {
            if (res.data.code == "200") {
                // res.dta.data
                res.data.data.forEach(item => {
                    dataset.push([item.x,item.val]);
                });
                cb && cb();
            }
        })
}

function drawBar() {
    // 绘制图表
    myChart.setOption({
        title: {
            text: 'ECharts 入门示例'
        },
        tooltip: {

        },
        xAxis: { type: 'category' },
        yAxis: {},
        dataset: {
            // 提供一份数据。
            source: [
                ['product', '销量'],
                ...dataset
            ]
        },
        series: [
            {
                name: '销量',
                type: 'bar',
            }
        ]
    });
}

onMounted(() => {    
    // 基于准备好的dom，初始化echarts实例
    myChart = echarts.init(document.getElementById('bar-box'), 'dark');

    getSaleData(drawBar);
})



function resizeChart() {
    myChart?.resize();
}

window.addEventListener('resize', resizeChart);

onBeforeUnmount(() => {
    window.removeEventListener("resize", resizeChart)
})

</script>

<template>
    <div id="bar-box">

    </div>
</template>

<style  scoped>
#bar-box {
    width: 100%;
    height: 100%;
}
</style>
